import { currentFileAtom, focusItemAtom, selectedKeysAtom } from '@renderer/store/jotai'
import { ref, watch } from 'vue'
import { setCurrentFileToLocal, setSelectedKeysToLocal } from '@renderer/store/localstorage'

import { useAtom } from 'jotai-vue'
import useFileTree from '../useFileTree'
import useOpenKeys from '../useOpenKeys'

export default function useCurrentFile() {
  const [selectedKeys, setSelectedKeys] = useAtom(selectedKeysAtom)
  const [currentFile, setCurrentFile] = useAtom(currentFileAtom)
  const { addOpenKeys } = useOpenKeys()
  const [, setFocusItem] = useAtom(focusItemAtom)
  const { fileTree } = useFileTree()

  const findFileParentIds = (fileId, fileTree, parentIds = []) => {
    let parentItem

    const items = Object.values(fileTree)

    for (const item of items) {
      if (item.children?.includes(fileId)) {
        parentItem = item
        break
      }
    }

    if (parentItem) {
      const parentId = parentItem.data.id
      parentIds.push(parentId)
      parentIds = [...parentIds, ...findFileParentIds(parentId, fileTree, parentIds)]
    }

    return parentIds
  }

  const updateCurrentFile = async (fileInfo) => {
    const fileId = fileInfo?.id
    const keys = fileId ? [fileId] : []
    setSelectedKeys(keys)
    setSelectedKeysToLocal(keys)

    setCurrentFileToLocal(fileInfo)
    setCurrentFile(fileInfo)

    setFocusItem(fileId || '')

    if (fileId) {
      const parentIds = findFileParentIds(fileId, fileTree.value)

      if (parentIds.length) {
        addOpenKeys(parentIds)
      }
    }

    return fileInfo
  }

  // Watch for changes in fileTree and update parentIds accordingly
  watch(fileTree, (newValue) => {
    if (currentFile.value && fileTree.value) {
      const parentIds = findFileParentIds(currentFile.value.id, newValue)
      if (parentIds.length) {
        addOpenKeys(parentIds)
      }
    }
  })

  return {
    currentFile: ref(currentFile.value),
    selectedKeys: ref(selectedKeys.value),
    updateCurrentFile,
    setCurrentFile
  }
}
